#!/usr/bin/env julia

"""
DRP-4DVar Integration Validation Script

This script provides a quick validation of the DRP-4DVar integration with
the GSI framework. It runs a minimal test to ensure all components are
working correctly and can be used as a smoke test for the integration.

Usage:
    julia test_integration_validation.jl [--verbose] [--full-test]

Options:
    --verbose    Show detailed output
    --full-test  Run comprehensive integration tests
"""

using Pkg

# Add the current directory to the load path
push!(LOAD_PATH, "src")

try
    # Test basic module loading
    println("="^60)
    println("DRP-4DVAR INTEGRATION VALIDATION")
    println("="^60)
    
    verbose = "--verbose" in ARGS
    full_test = "--full-test" in ARGS
    
    println("\n1. Testing Module Loading...")
    
    # Load core module
    include("src/GSICoreAnalysis.jl")
    using .GSICoreAnalysis
    println("✓ GSICoreAnalysis module loaded successfully")
    
    # Test FourDVar module
    using .GSICoreAnalysis.FourDVar
    println("✓ FourDVar module loaded successfully")
    
    # Test GSI integration module
    using .GSICoreAnalysis.FourDVar.GSIIntegration
    println("✓ GSIIntegration module loaded successfully")
    
    println("\n2. Testing Core Functionality...")
    
    # Test DRP4DVar constructor
    drp4dvar = DRP4DVar(ensemble_size=10, max_outer_loops=2)
    println("✓ DRP4DVar constructor works")
    
    # Test interface constructors
    test_grid = (nx=6, ny=6, nsig=4)
    obs_interface = GSIObservationInterface(test_grid)
    println("✓ GSIObservationInterface constructor works")
    
    println("\n3. Testing Integration Components...")
    
    # Create small test case
    if verbose
        println("  Creating small atmospheric test case...")
    end
    
    test_case = create_atmospheric_test_case(
        "validation_test",
        nx = 6, ny = 6, nz = 4,
        time_window = 2,
        n_obs_per_time = 10,
        obs_types = [:temperature]
    )
    
    println("✓ Atmospheric test case creation works")
    if verbose
        println("    Test case: $(test_case.name)")
        println("    Domain: $(test_case.domain_type)")
        println("    State size: $(length(test_case.background_field))")
        println("    Observations: $(test_case.n_observations)")
    end
    
    println("\n4. Testing DRP-4DVar Execution...")
    
    # Run minimal DRP-4DVar analysis
    if verbose
        println("  Running DRP-4DVar with minimal configuration...")
    end
    
    result = run_operational_drp4dvar(
        test_case,
        ensemble_size = 6,
        max_outer_loops = 2,
        convergence_tolerance = 1e-4
    )
    
    println("✓ DRP-4DVar execution successful")
    
    # Validate result structure
    required_keys = ["analysis_state", "analysis_increment", "statistics", "innovation_statistics"]
    for key in required_keys
        if haskey(result, key)
            println("✓ Result contains '$key'")
        else
            println("✗ Result missing '$key'")
        end
    end
    
    if verbose
        stats = result["statistics"]
        println("    Execution time: $(get(stats, "total_execution_time", "N/A")) seconds")
        println("    Converged: $(get(stats, "converged", "N/A"))")
        println("    Final cost: $(get(stats, "final_cost", "N/A"))")
    end
    
    println("\n5. Testing GSI Framework Integration...")
    
    # Test GSI run_analysis interface
    gsi_config = AnalysisConfig(
        grid_size = (6, 6, 4),
        nvars = 5,
        precision = Float64,
        params = Dict(
            "ensemble_size" => 6,
            "time_window" => 2,
            "max_outer_loops" => 2
        )
    )
    
    gsi_data = Dict(
        "background_state" => test_case.background_field,
        "background_error_operator" => test_case.background_error,
        "observation_operators" => test_case.observation_operators,
        "model_operators" => test_case.model_operators
    )
    
    gsi_observations = Dict(
        string(k) => v for (k, v) in test_case.observations
    )
    
    if verbose
        println("  Running through GSI interface...")
    end
    
    gsi_result = run_analysis("4DVar", gsi_data, gsi_observations, gsi_config)
    
    println("✓ GSI framework integration works")
    
    if haskey(gsi_result, "method") && gsi_result["method"] == "DRP-4DVar"
        println("✓ Method correctly identified as DRP-4DVar")
    else
        println("⚠ Method identification issue")
    end
    
    # Run full comprehensive tests if requested
    if full_test
        println("\n6. Running Comprehensive Tests...")
        
        try
            include("test/test_drp4dvar_realistic_integration.jl")
            println("✓ Comprehensive integration tests completed")
        catch e
            println("⚠ Comprehensive tests encountered issues: $e")
        end
    end
    
    # Validation summary
    println("\n" * "="^60)
    println("INTEGRATION VALIDATION SUMMARY")
    println("="^60)
    
    println("✓ Module loading and imports successful")
    println("✓ Core DRP-4DVar functionality operational")
    println("✓ GSI integration components working")
    println("✓ Atmospheric test case generation functional")
    println("✓ End-to-end DRP-4DVar execution successful")
    println("✓ GSI framework integration validated")
    
    if full_test
        println("✓ Comprehensive integration tests completed")
    end
    
    println("\n🎉 INTEGRATION VALIDATION: PASSED")
    println("\nThe DRP-4DVar integration with GSI framework is working correctly!")
    println("You can now use the integrated system for realistic atmospheric")
    println("data assimilation applications.")
    
    if !full_test
        println("\nFor comprehensive validation, run:")
        println("julia test_integration_validation.jl --full-test")
    end
    
    println("\n" * "="^60)

catch e
    println("\n" * "="^60)
    println("❌ INTEGRATION VALIDATION: FAILED")
    println("="^60)
    
    println("Error encountered during validation:")
    println("$e")
    
    if isa(e, LoadError)
        println("\nThis appears to be a module loading error.")
        println("Please ensure all dependencies are properly installed.")
    elseif isa(e, MethodError)
        println("\nThis appears to be a method or function error.")
        println("Please check that all required functions are exported.")
    else
        println("\nUnexpected error type. Please check the implementation.")
    end
    
    println("\nTroubleshooting steps:")
    println("1. Ensure Julia environment is set up correctly")
    println("2. Check that all required dependencies are installed")
    println("3. Verify module structure and exports")
    println("4. Review error messages for specific issues")
    
    println("\n" * "="^60)
    exit(1)
end
